package multithread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xi on 2019/2/17.
 * Lock接口的 线程请求锁的 几个方法：
 lock(), 拿不到lock就不罢休，不然线程就一直block。 比较无赖的做法。
 tryLock()，马上返回，拿到lock就返回true，不然返回false。 比较潇洒的做法。
 带时间限制的tryLock()，拿不到lock，就等一段时间，超时返回false。比较聪明的做法。
 下面的lockInterruptibly()就稍微难理解一些。
 */
public class LockTest {


    public static void main(String[] args) throws Exception {
        LockTest  test = new LockTest();
        test.test3();
    }

   // lock()忽视interrupt() 异常, 拿不到锁就 一直阻塞：
    public void test3()throws Exception{
        final Lock lock=new ReentrantLock();
        lock.lock();
        Thread.sleep(1000);
        Thread t1=new Thread(new Runnable(){
            @Override
            public void run(){
                System.out.println("test3");
                lock.lock();
                System.out.println(Thread.currentThread().getName()+" interrupted.");
            }
        });
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
       // Thread.sleep(1000000);
    }

    // lockInterruptibly()会响应打扰 并catch到InterruptedException
    public synchronized  void test4()throws Exception{
        final Lock lock=new ReentrantLock();
        lock.lock();
        Thread.sleep(1000);
        Thread t1=new Thread(new Runnable(){
            @Override
            public void run(){
                try{
                    lock.lockInterruptibly();
                }catch(InterruptedException e){
                    System.out.println(Thread.currentThread().getName()+" interrupted.");
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
       // Thread.sleep(1000000);
    }


    //以下实验验证：当线程已经被打扰了（isInterrupted()返回true）。则线程使用lock.lockInterruptibly()，直接会被要求处理InterruptedException。
    public void test5()throws Exception{
        final Lock lock=new ReentrantLock();
        lock.lock();
        Thread.sleep(1000);
        Thread t1=new Thread(new Runnable(){
            @Override
            public void run(){
                try{
                    Thread.sleep(2000);
                    System.out.println("232323");
                    lock.lockInterruptibly();
                }catch(InterruptedException e){
                    System.out.println(Thread.currentThread().getName()+" interrupted.");
                }
            }
        });
        t1.start();
        t1.interrupt();
    }
}
